<!-- employeeDetailPage.vue -->
<template>
  <div class="employee-detail-container">
    <el-card class="employee-basic-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
        </div>
      </template>

      <el-form ref="employeeForm" :model="employeeData" :rules="employeeRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <input-widget-web v-model="employeeData.name" label="员工姓名" prop="name" :readonly="!editMode"
              :rules="[{ required: true, message: '员工姓名不能为空', trigger: 'blur' }]" />
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" :class="{ 'readonly-form-item': !editMode }">
              <span v-if="!editMode" class="readonly-content">
                {{ genderText }}
              </span>
              <el-select v-else v-model="employeeData.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="未知" :value="0" />
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <input-widget-web v-model="employeeData.mobNumber" label="手机号" prop="mobNumber" :readonly="!editMode"
              :rules="[{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]" />
          </el-col>

          <el-col :span="12">
            <el-form-item label="入职日期" :class="{ 'readonly-form-item': !editMode }">
              <span v-if="!editMode" class="readonly-content">
                {{ joinDateText }}
              </span>
              <el-date-picker v-else v-model="employeeData.joinDate" type="date" placeholder="请选择入职日期"
                style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>



        <el-row :gutter="20">
          <el-col :span="12">
            <input-widget-web v-model="employeeData.email" label="邮箱" prop="email" :readonly="!editMode" />
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态" :class="{ 'readonly-form-item': !editMode }">
              <span v-if="!editMode" class="readonly-content">
                <el-tag :type="employeeData.available ? 'success' : 'danger'">
                  {{ employeeData.available ? '启用' : '禁用' }}
                </el-tag>
              </span>
              <el-switch v-else v-model="employeeData.available" active-text="启用" inactive-text="禁用"
                :disabled="isCurrentUser" />
            </el-form-item>
          </el-col>
        </el-row>

        <input-widget-web v-model="employeeData.remark" label="备注" prop="remark" :readonly="!editMode"
          placeholder="请输入备注" :remarkMode="true" />
      </el-form>
    </el-card>

    <el-card class="employee-account-card">
      <template #header>
        <div class="card-header">
          <span>账户信息</span>
        </div>
      </template>

      <el-form label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <input-widget-web v-model="employeeData.userName" label="登录账号" prop="userName" :readonly="!editMode" />
          </el-col>

          <el-col :span="12">
            <el-form-item label="登录权限" :class="{ 'readonly-form-item': !editMode }">
              <span v-if="!editMode" class="readonly-content">
                <el-tag :type="employeeData.loginAuthorized ? 'success' : 'info'">
                  {{ employeeData.loginAuthorized ? '有权限' : '无权限' }}
                </el-tag>
              </span>
              <el-switch v-else v-model="employeeData.loginAuthorized" active-text="有权限" inactive-text="无权限" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="editMode && !employeeData.id">
          <el-col :span="12">
            <input-widget-web v-model="employeeData.resetPwd" label="设置密码" prop="resetPwd" :disabled="false"
              show-password />
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="employee-role-card">
      <template #header>
        <div class="card-header">
          <span>角色分配</span>
        </div>
      </template>

      <div v-if="!editMode" class="readonly-role-content">
        <el-tag v-for="role in selectedRoles" :key="role.id" style="margin-right: 10px; margin-bottom: 10px;">
          {{ role.name }}
        </el-tag>
        <span v-if="selectedRoles.length === 0">-</span>
      </div>

      <el-checkbox-group v-else v-model="selectedRoleIds" style="padding: 20px;">
        <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id"
          style="margin-right: 20px; margin-bottom: 10px;">
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>
    </el-card>

    <div class="form-actions">
      <el-button v-if="!editMode" type="primary" @click="editMode = true">编辑</el-button>
      <template v-else>
        <el-button type="primary" @click="saveEmployee">保存</el-button>
        <el-button @click="cancelEdit">取消</el-button>
      </template>
      <el-button @click="closePage">关闭</el-button>
    </div>
  </div>
</template>

<script>
import { ElMessage, ElTag } from 'element-plus'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction'
import { Engine } from '../../public/engine/engine'
import { Employee } from '../../public/engine/enterpriseMgt/employee'
import { DateUtil } from '../../public/utils/dateUtil'
import EventBus from '../../public/engine/ipc/eventBus'
import TabUtil from '@/plugins/tab'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'

export default {
  name: 'employeeDetail',

  components: {
    InputWidgetWeb,
    ElTag
  },

  data() {
    return {
      employeeData: {
        id: undefined,
        name: '',
        jobNumber: '',
        gender: 0,
        mobNumber: '',
        joinDate: new Date(),
        title: '',
        email: '',
        loginAuthorized: false,
        userName: '',
        resetPwd: '123456',
        available: true,
        remark: '',
        role: []
      },

      employeeRules: {
        name: [
          { required: true, message: '员工姓名不能为空', trigger: 'blur' }
        ],
        mobNumber: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },

      roleList: [],
      selectedRoleIds: [],
      enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
      orgId: Engine.profile.org.orgId,
      loading: false,
      employee: Employee.empty(),
      retValue: null,
      editMode: false,
      originalEmployeeData: null
    }
  },

  computed: {
    isCurrentUser() {
      return this.employeeData.id === Engine.profile.id
    },

    genderText() {
      const genders = { 0: '未知', 1: '男', 2: '女' }
      return genders[this.employeeData.gender] || '未知'
    },

    joinDateText() {
      return this.employeeData.joinDate ? DateUtil.getDayTitle(this.employeeData.joinDate) : '-'
    },

    selectedRoles() {
      return this.roleList.filter(role => this.selectedRoleIds.includes(role.id))
    }
  },

  async mounted() {
    // Get role list
    await this.getRoleList()

    // Load employee data if editing   
    await this.loadEmployeeData()

    // Set edit mode based on route
    this.editMode = !this.$route.query.id
  },

  beforeUnmount() {
    if (this.retValue) {
      EventBus.emit('employeeDataUpdated', null)
      this.retValue = null
    }
  },

  deactivated() {
    if (this.retValue) {
      EventBus.emit('employeeDataUpdated', null)
      this.retValue = null
    }
  },

  methods: {
    async getRoleList() {
      try {
        const res = await this.enterpriseMgtUiAction.getRoleData({
          pageInfo: { curIndex: 1, limitPerPage: 100 }
        })

        if (res?.data?.dataList) {
          this.roleList = res.data.dataList
        }
      } catch (error) {
        console.error('获取角色列表失败', error)
        ElMessage.error('获取角色列表失败')
      }
    },

    async loadEmployeeData() {
      try {
        this.loading = true
        const id = this.$route.query.id

        if (!id) {
          // For new employee, save initial state
          this.originalEmployeeData = JSON.parse(JSON.stringify(this.employeeData))
          return
        }

        // Get employee data from API
        const employeeInfo = await this.enterpriseMgtUiAction.getEmployeeDetailInfo(id)

        if (employeeInfo) {
          this.employee = employeeInfo
          this.employeeData = {
            id: employeeInfo.id,
            name: employeeInfo.name,
            jobNumber: employeeInfo.jobNumber,
            gender: employeeInfo.gender,
            mobNumber: employeeInfo.mobNumber,
            joinDate: employeeInfo.joinDate,
            title: employeeInfo.title,
            email: employeeInfo.email,
            loginAuthorized: employeeInfo.loginAuthorized,
            userName: employeeInfo.userName,
            resetPwd: employeeInfo.resetPwd,
            available: employeeInfo.available,
            remark: employeeInfo.remark
          }

          // Set selected roles
          this.selectedRoleIds = employeeInfo.role.map(r => r.id)

          // Save original state for cancel operation
          this.originalEmployeeData = JSON.parse(JSON.stringify(this.employeeData))
        }
      } catch (error) {
        console.error('加载员工数据失败', error)
        ElMessage.error('加载员工数据失败')
      } finally {
        this.loading = false
      }
    },

    async saveEmployee() {
      try {
        // Validate form
        await this.$refs.employeeForm.validate()

        this.loading = true

        // Prepare employee data
        const employeeParams = new Employee({
          id: this.employeeData.id,
          name: this.employeeData.name,
          jobNumber: this.employeeData.jobNumber,
          gender: this.employeeData.gender,
          mobNumber: this.employeeData.mobNumber,
          joinDate: DateUtil.strToDate(this.employeeData.joinDate),
          title: this.employeeData.title,
          email: this.employeeData.email,
          loginAuthorized: this.employeeData.loginAuthorized,
          userName: this.employeeData.userName,
          resetPwd: this.employeeData.resetPwd,
          available: this.employeeData.available,
          remark: this.employeeData.remark,
          role: this.roleList.filter(r => this.selectedRoleIds.includes(r.id))
        })

        // Save employee data
        const res = await this.enterpriseMgtUiAction.updateOrCreateEmployeeData(employeeParams)

        if (res) {
          this.retValue = employeeParams
          ElMessage.success(this.employee.id ? '员工信息更新成功' : '员工创建成功')

          if (!this.employee.id) {
            setTimeout(() => {
              TabUtil.closePage()
            }, 1000)
          } else {
            EventBus.emit('employeeDataUpdated', null)
            this.editMode = false
            this.originalEmployeeData = JSON.parse(JSON.stringify(this.employeeData))
          }
        }
      } catch (error) {
        console.error('保存员工失败', error)
        ElMessage.error('保存员工失败')
      } finally {
        this.loading = false
      }
    },

    cancelEdit() {
      // Restore original data
      if (this.originalEmployeeData) {
        this.employeeData = JSON.parse(JSON.stringify(this.originalEmployeeData))
      }
      this.editMode = false
    },

    closePage() {
      TabUtil.closePage()
    }
  }
}
</script>

<style scoped>
.employee-detail-container {
  padding: 20px;
  max-width: 1200px;
}

.employee-basic-card,
.employee-account-card,
.employee-role-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}

.form-actions {
  padding: 20px 0;
  text-align: center;
}

.form-actions .el-button {
  margin: 0 10px;
}

.readonly-form-item :deep(.el-form-item__label) {
  font-size: 13px;
  color: #909399;
}

.readonly-content {
  display: flex;
  align-items: center;
  width: 400px;
  padding: 0 10px;
  height: 40px;
  font-size: 15px;
  color: #303133;
  vertical-align: middle;
  margin-top: -5px;
}

.readonly-form-item :deep(.el-form-item__label::before) {
  content: none !important;
}

.readonly-role-content {
  padding: 20px;
  min-height: 40px;
}
</style>